package pers.qianyu.month_202012.date_20201229;

import org.junit.*;

/**
 * @author mizzle rain
 * @date 2020-12-29 21:28
 */
public class AddBinary {
    public String addBinary(String a, String b) {
        StringBuilder sa = new StringBuilder(a);
        StringBuilder sb = new StringBuilder(b);
        sa.reverse();
        sb.reverse();
        int lenA = sa.length();
        int lenB = sb.length();
        // 进位
        int carry = 0;
        StringBuilder res = new StringBuilder();
        int p = 0;
        for (; p < lenA || p < lenB; p++) {
            int numA = p < lenA ? sa.charAt(p) - '0' : 0;
            int numB = p < lenB ? sb.charAt(p) - '0' : 0;
            int sum = numA + numB + carry;
            carry = sum / 2;
            res.append(sum % 2);
        }
        if (carry > 0) {
            res.append(carry);
        }
        return res.reverse().toString();
    }

    public String addBinary0(String a, String b) {
        return Integer.toBinaryString(
                Integer.parseInt(a, 2) + Integer.parseInt(b, 2));
    }

    @Test
    public void test1() {
        AddBinary s = new AddBinary();
        String a = "11";
        String b = "1";
        String result = s.addBinary(a, b);
        Assert.assertEquals(result, s.addBinary0(a, b));
    }

    @Test
    public void test2() {
        AddBinary s = new AddBinary();
        String a = "1010";
        String b = "1011";
        String result = s.addBinary(a, b);
        Assert.assertEquals(result, s.addBinary0(a, b));
    }
}

/*
python 骚操作：
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return bin(int(a,2) + int(b,2))[2:]
 */